﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace App.AuthenJwt
{
    public static class JwtExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="signKey">jwt 秘钥</param>
        /// <param name="issuer">发行人</param>
        /// <param name="audience">使用人</param>
        public static void UseJwtExtension(this IServiceCollection services, string signKey, string issuer, string audience)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              .AddJwtBearer(option =>
              {
                  option.SaveToken = true;
                  option.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey)),
                      ValidateIssuer = true,  // 验证发行者
                      ValidIssuer = issuer,
                      ValidateAudience = true, // 验证使用者
                      ValidAudience = audience,
                      ValidateLifetime = true, // 验证有效期

                      // 缓冲时间
                      ClockSkew = TimeSpan.FromSeconds(30),
                  };
              });
        }
    }
}
